import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store/store';

const Main = () => import('../views/Main');
const Login = () => import('../views/Login/login.vue');

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  {
    name: 'Main',
    path: '/',
    component: Main,
    redirect: '/home',
    children: [],
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
];

const router = new VueRouter({
  mode: 'history',
  routes,
});

router.beforeEach((to, from, next) => {
  store.commit('user/getToken');
  const token = store.state.user.token;
  if (!token && to.name !== 'login') {
    next({ name: 'login' });
  } else if (token && to.name === 'login') {
    next({ name: 'home' });
  } else {
    next();
  }
});

export default router;
